<!-- 代码已包含 CSS：使用 TailwindCSS , 安装 TailwindCSS 后方可看到布局样式效果 -->

<template>
    <div class="min-h-screen bg-gray-50">
        <!-- Header -->
        <header class="bg-white shadow-sm">
            <div class="mx-auto max-w-7xl px-4 py-6 sm:px-6 lg:px-8">
                <h1 class="text-3xl font-bold text-gray-900">九型人格测试</h1>
            </div>
        </header>

        <!-- Main Content -->
        <main class="mx-auto max-w-7xl px-4 py-6 sm:px-6 lg:px-8">
            <!-- Introduction Card -->
            <div v-if="currentStage === 'intro'" class="bg-white shadow rounded-lg p-8 mb-8">
                <h2 class="text-2xl font-semibold text-gray-800 mb-6">九型人格测试简介</h2>
                <div class="prose max-w-none text-gray-600 mb-8">
                    <p>九型人格是一种深层次了解人的方法和学问，它按照人们的思维、情绪和行为，将人分为九种类型。</p>
                    <p>本测试包含 144 道题目，每道题目包含两个选项，您需要选择最符合您情况的选项。</p>
                    <p>测试大约需要 45 分钟完成，请在一个安静的环境中认真作答。</p>
                    <p>测试结果将帮助您更好地了解自己的性格特点、优势和潜在的发展方向。</p>
                </div>
                <div class="flex justify-center">
                    <button
                        @click="startTest"
                        class="!rounded-button whitespace-nowrap bg-indigo-600 px-6 py-3 text-white font-medium hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2"
                    >
                        开始测试
                    </button>
                </div>
            </div>

            <!-- Test Area -->
            <div v-if="currentStage === 'test'" class="bg-white shadow rounded-lg p-8">
                <!-- Progress and Timer -->
                <div class="flex justify-between items-center mb-8">
                    <div class="w-full bg-gray-200 rounded-full h-2.5">
                        <div class="bg-indigo-600 h-2.5 rounded-full" :style="{ width: `${(currentQuestionIndex / questions.length) * 100}%` }"></div>
                    </div>
                    <div class="ml-4 text-gray-600">剩余时间: {{ formatTime(remainingTime) }}</div>
                </div>

                <!-- Question -->
                <div class="mb-8">
                    <h2 class="text-xl font-semibold text-gray-800 mb-4">题目 {{ currentQuestionIndex + 1 }} / {{ questions.length }}</h2>
                    <p class="text-lg text-gray-700 mb-6">{{ currentQuestion.text }}</p>

                    <!-- Options -->
                    <div class="space-y-4">
                        <div
                            v-for="(option, index) in currentQuestion.options"
                            :key="index"
                            @click="selectOption(index)"
                            class="p-4 border rounded-lg cursor-pointer transition-colors"
                            :class="{
                                'border-indigo-500 bg-indigo-50': selectedOption === index,
                                'border-gray-300 hover:border-indigo-300': selectedOption !== index,
                            }"
                        >
                            <div class="flex items-center">
                                <div
                                    class="w-6 h-6 rounded-full border flex items-center justify-center mr-3"
                                    :class="{
                                        'border-indigo-500': selectedOption === index,
                                        'border-gray-400': selectedOption !== index,
                                    }"
                                >
                                    <div v-if="selectedOption === index" class="w-3 h-3 rounded-full bg-indigo-500"></div>
                                </div>
                                <span class="text-gray-700">{{ option }}</span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Navigation -->
                <div class="flex justify-between">
                    <button
                        v-if="currentQuestionIndex > 0"
                        @click="prevQuestion"
                        class="!rounded-button whitespace-nowrap bg-white px-4 py-2 border border-gray-300 text-gray-700 font-medium hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2"
                    >
                        上一题
                    </button>
                    <div v-else></div>
                    <button
                        @click="nextQuestion"
                        :disabled="selectedOption === null"
                        class="!rounded-button whitespace-nowrap bg-indigo-600 px-6 py-2 text-white font-medium hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                        {{ currentQuestionIndex === questions.length - 1 ? '查看结果' : '下一题' }}
                    </button>
                </div>
            </div>

            <!-- Results -->
            <div v-if="currentStage === 'results'" class="bg-white shadow rounded-lg p-8">
                <h2 class="text-2xl font-semibold text-gray-800 mb-6">您的九型人格测试结果</h2>

                <!-- Radar Chart -->
                <div class="mb-8">
                    <h3 class="text-lg font-medium text-gray-700 mb-4">人格特质分布</h3>
                    <div ref="radarChart" class="h-96"></div>
                </div>

                <!-- Bar Chart -->
                <div class="mb-8">
                    <h3 class="text-lg font-medium text-gray-700 mb-4">各维度得分</h3>
                    <div ref="barChart" class="h-96"></div>
                </div>

                <!-- Personality Description -->
                <div class="mb-8">
                    <h3 class="text-lg font-medium text-gray-700 mb-4">主要人格类型</h3>
                    <div class="prose max-w-none text-gray-600">
                        <p>
                            根据测试结果，您的主要人格类型是 <strong>{{ primaryType.name }}</strong> ({{ primaryType.type }})。
                        </p>
                        <p>{{ primaryType.description }}</p>
                    </div>
                </div>

                <!-- Traits Analysis -->
                <div class="mb-8">
                    <h3 class="text-lg font-medium text-gray-700 mb-4">个性特征分析</h3>
                    <div class="prose max-w-none text-gray-600">
                        <ul>
                            <li v-for="(trait, index) in primaryType.traits" :key="index">{{ trait }}</li>
                        </ul>
                    </div>
                </div>

                <!-- Development Suggestions -->
                <div class="mb-8">
                    <h3 class="text-lg font-medium text-gray-700 mb-4">发展建议</h3>
                    <div class="prose max-w-none text-gray-600">
                        <ul>
                            <li v-for="(suggestion, index) in primaryType.suggestions" :key="index">{{ suggestion }}</li>
                        </ul>
                    </div>
                </div>

                <!-- Actions -->
                <div class="flex justify-center space-x-4">
                    <button
                        @click="downloadPDF"
                        class="!rounded-button whitespace-nowrap bg-white px-4 py-2 border border-gray-300 text-gray-700 font-medium hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2"
                    >
                        导出 PDF
                    </button>
                    <button
                        @click="restartTest"
                        class="!rounded-button whitespace-nowrap bg-indigo-600 px-6 py-2 text-white font-medium hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2"
                    >
                        重新测试
                    </button>
                </div>
            </div>
        </main>
    </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, nextTick, watch } from 'vue'
import * as echarts from 'echarts'

// 九型人格类型定义
const enneagramTypes = [
    {
        type: '1',
        name: '完美型',
        description: '完美型的人理性正直，追求进步，力图把每件事都做得尽善尽美，希望自己和他人都能不断进步。',
        traits: ['追求完美，对自己和他人要求严格', '有强烈的道德感和责任感', '注重细节，做事有条理', '容易看到错误和不足', '内心常有自我批评'],
        suggestions: [
            '学会接受不完美，理解完美是相对的',
            '培养对自己和他人的宽容心',
            '适当放松标准，享受过程而非只关注结果',
            '学习区分重要和不重要的细节',
        ],
    },
    {
        type: '2',
        name: '助人型',
        description: '助人型的人慷慨大方，乐于助人，渴望被爱和被需要，常常将他人的需求置于自己之上。',
        traits: [
            '富有同情心，善于理解他人需求',
            '乐于付出，常常忽视自己的需要',
            '渴望被爱和被需要',
            '有时会过度介入他人的生活',
            '情感丰富，善于表达关怀',
        ],
        suggestions: ['学会平衡给予和接受的关系', '关注并表达自己的需求', '建立健康的界限，避免过度付出', '认识到自我价值不依赖于他人的认可'],
    },
    {
        type: '3',
        name: '成就型',
        description: '成就型的人注重效率，追求成功，渴望被认可和赞赏，常常以成就来衡量自我价值。',
        traits: ['目标导向，注重效率和结果', '适应能力强，善于自我调整', '渴望成功和被认可', '有时会忽视情感和人际关系', '形象意识强，注重外在表现'],
        suggestions: ['关注内在价值而非外在成就', '培养真诚的人际关系', '学会接受失败和挫折', '平衡工作和生活，关注情感需求'],
    },
    {
        type: '4',
        name: '自我型',
        description: '自我型的人敏感细腻，富有创造力，渴望独特性和深度，常常沉浸在情感和想象中。',
        traits: ['情感丰富，富有创造力', '追求独特性和真实性', '对美和深度有强烈感知', '情绪波动较大', '有时会感到与他人不同'],
        suggestions: ['培养情绪管理能力', '平衡理想与现实', '认识到平凡中的美', '通过艺术表达释放情感'],
    },
    {
        type: '5',
        name: '思考型',
        description: '思考型的人理性客观，善于分析，渴望知识和理解，常常保持情感上的距离。',
        traits: ['求知欲强，善于分析和思考', '注重隐私和个人空间', '情感上保持一定距离', '观察多于参与', '对复杂问题有深入理解'],
        suggestions: ['更多地参与实际生活', '表达情感和想法', '平衡思考与行动', '与他人分享知识和见解'],
    },
    {
        type: '6',
        name: '忠诚型',
        description: '忠诚型的人忠诚可靠，注重安全，常常考虑潜在的危险和问题，寻求支持和确定性。',
        traits: ['忠诚可靠，责任感强', '考虑问题全面，预见潜在风险', '寻求安全感和确定性', '有时会过度担忧', '对权威有矛盾心理'],
        suggestions: ['培养对不确定性的容忍度', '区分真实和想象的威胁', '建立自信心', '平衡怀疑和信任'],
    },
    {
        type: '7',
        name: '活跃型',
        description: '活跃型的人乐观开朗，追求快乐，渴望多样性和新体验，常常逃避痛苦和限制。',
        traits: ['乐观积极，充满活力', '追求多样性和新体验', '善于看到可能性', '有时会逃避痛苦和限制', '思维跳跃，兴趣广泛'],
        suggestions: ['培养专注力和持久性', '面对而非逃避困难', '平衡快乐与责任', '深入发展某些领域'],
    },
    {
        type: '8',
        name: '领袖型',
        description: '领袖型的人果断自信，保护他人，渴望控制和影响，常常表现出强势和直接。',
        traits: ['果断自信，行动力强', '保护弱小，伸张正义', '渴望控制和自主权', '直接坦率，有时显得强势', '厌恶被控制和软弱'],
        suggestions: ['培养耐心和倾听能力', '适当展现脆弱性', '平衡力量与温柔', '考虑他人感受和需求'],
    },
    {
        type: '9',
        name: '和平型',
        description: '和平型的人平和包容，避免冲突，渴望和谐与舒适，常常顺应他人和现状。',
        traits: ['平和包容，善于调解', '避免冲突，寻求和谐', '顺应他人和现状', '有时会忽视自己的需求', '行动缓慢，优柔寡断'],
        suggestions: ['表达自己的观点和需求', '培养决断力和行动力', '认识到冲突有时是必要的', '平衡他人需求与自我需求'],
    },
]

// 测试题目 (示例题目，实际应有144道)
const questions = Array.from({ length: 5 }, (_, i) => ({
    id: i + 1,
    text: `题目 ${i + 1}: 在以下两种描述中，哪一种更符合您的情况？`,
    options: [
        `选项 A: ${['我更注重把事情做对', '我喜欢帮助他人', '我追求成功和成就', '我渴望独特和深度', '我喜欢分析和思考', '我考虑潜在的风险', '我追求快乐和新体验', '我果断自信', '我寻求和谐与平静'][i % 9]}`,
        `选项 B: ${['我更注重与人相处', '我关注自己的需求', '我重视情感和关系', '我理性客观', '我参与实际行动', '我相信事情会顺利', '我面对困难和责任', '我考虑他人感受', '我表达自己的观点'][i % 9]}`,
    ],
    // 每个问题对应的人格类型权重 (示例)
    weights: Array(9)
        .fill(0)
        .map((_, j) => Math.random() * 2 - 1), // 随机权重用于演示
}))

// 状态管理
const currentStage = ref<'intro' | 'test' | 'results'>('intro')
const currentQuestionIndex = ref(0)
const selectedOption = ref<number | null>(null)
const answers = ref<number[]>(Array(questions.length).fill(-1))
const remainingTime = ref(45 * 60) // 45分钟
const timer = ref<NodeJS.Timeout | null>(null)
const radarChart = ref<HTMLElement | null>(null)
const barChart = ref<HTMLElement | null>(null)

// 当前问题
const currentQuestion = computed(() => questions[currentQuestionIndex.value])

// 开始测试
const startTest = () => {
    currentStage.value = 'test'
    startTimer()
}

// 计时器
const startTimer = () => {
    if (timer.value) clearInterval(timer.value)
    timer.value = setInterval(() => {
        remainingTime.value--
        if (remainingTime.value <= 0) {
            finishTest()
        }
    }, 1000)
}

// 格式化时间
const formatTime = (seconds: number) => {
    const mins = Math.floor(seconds / 60)
    const secs = seconds % 60
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

// 选择选项
const selectOption = (index: number) => {
    selectedOption.value = index
    answers.value[currentQuestionIndex.value] = index
}

// 上一题
const prevQuestion = () => {
    if (currentQuestionIndex.value > 0) {
        currentQuestionIndex.value--
        selectedOption.value = answers.value[currentQuestionIndex.value]
    }
}

// 下一题
const nextQuestion = () => {
    if (selectedOption.value === null) return

    if (currentQuestionIndex.value < questions.length - 1) {
        currentQuestionIndex.value++
        selectedOption.value = answers.value[currentQuestionIndex.value] !== -1 ? answers.value[currentQuestionIndex.value] : null
    } else {
        finishTest()
    }
}

// 计算得分
const calculateScores = () => {
    const scores = Array(9).fill(0)

    answers.value.forEach((answer, qIndex) => {
        if (answer !== -1) {
            questions[qIndex].weights.forEach((weight, typeIndex) => {
                scores[typeIndex] += weight * (answer === 0 ? 1 : -1)
            })
        }
    })

    // 归一化到0-100
    const maxScore = Math.max(...scores)
    const minScore = Math.min(...scores)
    return scores.map((score) => Math.round(((score - minScore) / (maxScore - minScore)) * 100))
}

// 主要人格类型
const primaryType = computed(() => {
    const scores = calculateScores()
    const maxIndex = scores.indexOf(Math.max(...scores))
    return enneagramTypes[maxIndex]
})

// 完成测试
const finishTest = () => {
    if (timer.value) clearInterval(timer.value)
    currentStage.value = 'results'

    nextTick(() => {
        initCharts()
    })
}

// 初始化图表
const initCharts = () => {
    if (!radarChart.value || !barChart.value) return

    const scores = calculateScores()

    // 雷达图
    const radarChartInstance = echarts.init(radarChart.value)
    radarChartInstance.setOption({
        animation: false,
        radar: {
            indicator: enneagramTypes.map((type, i) => ({
                name: `${type.type}型\n${type.name}`,
                max: 100,
            })),
            radius: '65%',
        },
        series: [
            {
                type: 'radar',
                data: [
                    {
                        value: scores,
                        name: '人格特质',
                        areaStyle: {
                            color: 'rgba(99, 102, 241, 0.3)',
                        },
                        lineStyle: {
                            color: 'rgba(99, 102, 241, 1)',
                        },
                        itemStyle: {
                            color: 'rgba(99, 102, 241, 1)',
                        },
                    },
                ],
            },
        ],
    })

    // 柱状图
    const barChartInstance = echarts.init(barChart.value)
    barChartInstance.setOption({
        animation: false,
        xAxis: {
            type: 'category',
            data: enneagramTypes.map((type) => `${type.type}型`),
            axisLabel: {
                interval: 0,
                rotate: 0,
            },
        },
        yAxis: {
            type: 'value',
            max: 100,
        },
        series: [
            {
                data: scores.map((score, i) => ({
                    value: score,
                    itemStyle: {
                        color: i === scores.indexOf(Math.max(...scores)) ? '#6366F1' : '#A5B4FC',
                    },
                })),
                type: 'bar',
                barWidth: '60%',
            },
        ],
    })

    // 窗口大小变化时重新调整图表
    window.addEventListener('resize', () => {
        radarChartInstance.resize()
        barChartInstance.resize()
    })
}

// 导出PDF
const downloadPDF = () => {
    alert('PDF导出功能需要后端支持，此处为演示')
}

// 重新测试
const restartTest = () => {
    currentStage.value = 'intro'
    currentQuestionIndex.value = 0
    selectedOption.value = null
    answers.value = Array(questions.length).fill(-1)
    remainingTime.value = 45 * 60
}

// 组件卸载时清除定时器
onMounted(() => {
    return () => {
        if (timer.value) clearInterval(timer.value)
    }
})

// 监听剩余时间
watch(remainingTime, (newVal) => {
    if (newVal <= 5 * 60 && newVal > 0) {
        console.log('剩余时间不足5分钟')
    } else if (newVal <= 0) {
        finishTest()
    }
})
</script>

<!-- <style>
@import '/@/assets/css/enneagram-tailwind.css';
</style> -->
<style scoped lang="scss">
/* 自定义样式 */
.prose ul {
    @apply list-disc pl-5 space-y-2;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .prose {
        @apply text-sm;
    }

    .prose ul {
        @apply pl-4;
    }
}
</style>
